package com.whmskj.xjlhsc.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.whmskj.xjlhbc.db.DataSource;
import com.whmskj.xjlhbc.db.DataSourceType;
import com.whmskj.xjlhbc.db.DynamicDataSourceContextHolder;
import com.whmskj.xjlhbc.domain.CorpMember;
import com.whmskj.xjlhbc.mapper.CorpMemberMapper;
import com.whmskj.xjlhbc.mapper.ScdbMapper;
import com.whmskj.xjlhsc.controller.vo.JtjcVo;
import com.whmskj.xjlhsc.entity.EquipmentSpareParts;
import com.whmskj.xjlhsc.entity.Sb02EquipmentCounterAccount;
import com.whmskj.xjlhsc.mapper.*;
import com.whmskj.xjlhsc.mobie.equipmentManage.entity.vo.*;
import com.whmskj.xjlhsc.entity.*;
import com.whmskj.xjlhsc.mapper.*;
import com.whmskj.xjlhsc.mobie.empProPlan.entity.ProPersonnelStandConfirm;
import com.whmskj.xjlhsc.mobie.empProPlan.mapper.ProPersonnelStandConfirmMapper;
import com.whmskj.xjlhsc.mobie.empProPlan.service.ProPersonnelStandConfirmService;
import com.whmskj.xjlhsc.mobie.equipmentManage.entity.vo.*;
import com.whmskj.xjlhsc.service.Sb02EquipmentCounterAccountService;
import com.whmskj.xjlhsc.service.Sb08tasksheetService;
import com.whmskj.xjlhsc.service.ShachangSbStoptimeService;
import com.whmskj.xjlhsc.utils.SCUtil;
import com.whmskj.xjlhsc.view.entity.vo.ClassesRunEfficiencyVo;
import com.whmskj.xjlhsc.view.entity.vo.DBJYiledVo;
import com.whmskj.xjlhsc.view.entity.vo.DeviceRunEfficiencyVo;
import com.whmskj.xjlhsc.view.entity.vo.StateVo;
import com.whmskj.xjlhsc.view.service.DeviceRealTimeService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
@Slf4j
public class Sb02EquipmentCounterAccountServiceImpl extends ServiceImpl<Sb02EquipmentCounterAccountMapper, Sb02EquipmentCounterAccount>
        implements Sb02EquipmentCounterAccountService {

    @Autowired
    private Sb02EquipmentCounterAccountMapper sb02EquipmentCounterAccountMapper;
    @Autowired
    private CorpMemberMapper corpMemberMapper;
    @Autowired
    private Yg01employeefilesMapper yg01employeefilesMapper;
    @Autowired
    private ShachangSbStoptimeService shachangSbStoptimeService;
    @Autowired
    private Sb08tasksheetService sb08tasksheetService;
    @Autowired
    private Sb08tasksheetMapper sb08tasksheetMapper;
    @Autowired
    private EquipmentsparepartsMapper equipmentsparepartsMapper;
    @Autowired
    private ScDbRealtimeMapper scDbRealtimeMapper;
    @Autowired
    private ProPersonnelStandConfirmMapper proPersonnelStandConfirmMapper;

    @Override
    public Map<String, List<Sb02EquipmentCounterAccount>> findEquipmentList() {
        List<Sb02EquipmentCounterAccount> list = list();
        return list.stream().collect(Collectors.groupingBy(Sb02EquipmentCounterAccount::getProcess));
    }

    @Override
    public List<Object> findZl(int id) {
        List<Object> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("key", "品种");
        map.put("value", "R40S");
        list.add(map);
        map = new HashMap<>();
        map.put("key", "品种");
        map.put("value", "R40S");
        list.add(map);
        map = new HashMap<>();
        map.put("key", "品种");
        map.put("value", "R40S");
        list.add(map);
        map = new HashMap<>();
        map.put("key", "品种");
        map.put("value", "R40S");
        list.add(map);
        return list;
    }

    @Override
    public Object findRealInfo(int id) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> dcxx = new HashMap<>();
        dcxx.put("classes", "暂无");
        dcxx.put("name", "暂无");
        dcxx.put("workshop", "暂无");
        dcxx.put("team", "暂无");
        dcxx.put("process", "暂无");
        dcxx.put("ts", DateUtil.now());
        List<Object> scsj = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("key", "机型");
        map.put("value", "1576");
        scsj.add(map);

        result.put("dcxx", dcxx);
        result.put("scsj", scsj);
        return result;
    }

    @Override
    public Page<Object> findRealInfoWbList(int id) {
        Page<Object> page = SCUtil.getPage();
        List<Object> records = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("lx", "保养");
        map.put("xm", "揩车");
        map.put("date", DateUtil.now());
        records.add(map);
        page.setRecords(records);
        return page;
    }

    @Override
    public Page<Object> findRealInfoStopList(int id) {
        Page<Object> page = SCUtil.getPage();
        List<Object> records = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("start", DateUtil.now());
        map.put("end", DateUtil.now());
        map.put("sc", DateUtil.formatBetween(100 * 1000));
        records.add(map);
        page.setRecords(records);
        return page;
    }

    @Override
    public Page<Object> findRealInfoCnList(int id) {
        Page<Object> page = SCUtil.getPage();
        List<Object> records = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("classes", DateUtil.today() + "夜班");
        map.put("cl", "0");
        map.put("nh", "0");
        map.put("ds", "0");
        map.put("xl", "0");
        records.add(map);
        page.setRecords(records);
        return page;
    }

    @Override
    public Object findParamInfo(int id) {
        List<Object> scsj = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("key", "品种");
        map.put("value", "R40S");
        scsj.add(map);
        return scsj;
    }

    @Override
    public Object findDnInfo(int id) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> dnxx = new HashMap<>();
        dnxx.put("bnh", 0);
        dnxx.put("znh", 0);
        dnxx.put("dl", 0);
        dnxx.put("dy", 0);
        dnxx.put("gl", 0);
        dnxx.put("dya", 0);
        dnxx.put("dyb", 0);
        dnxx.put("dyc", 0);
        dnxx.put("dla", 0);
        dnxx.put("dlb", 0);
        dnxx.put("dlc", 0);
        dnxx.put("zgl", 0);
        Map<String, Object> nhMap = new HashMap<>();
        List<String> data = get();
        List<Integer> value = data.stream().map(v -> 0).toList();
        nhMap.put("data", data);
        nhMap.put("value", value);
        result.put("dnxx", dnxx);
        result.put("nh", nhMap);
        return result;
    }

    @Override
    public Object findJtdbInfo(String ids, String start, String end) {
        LocalDate startDate = StringUtils.hasText(start) ? LocalDate.parse(start) : LocalDate.now().minusDays(1);
        LocalDate endDate = StringUtils.hasText(end) ? LocalDate.parse(end) : LocalDate.now();
        List<String> dates = get(startDate, endDate);
        List<Map<String, Object>> list = new ArrayList<>();
        String[] jtIds = ids.split(",");
        for (String date : dates) {
            for (String jtId : jtIds) {
                Map<String, Object> map = new HashMap<>();
                map.put("date", date);
                map.put("classes", "白班");
                map.put("jth", "1#");
                map.put("jtm", "细纱机");
                map.put("cl", "0");
                map.put("nh", "0");
                map.put("dsnh", "0");
                map.put("xl", "0");
                list.add(map);
                map = new HashMap<>();
                map.put("date", date);
                map.put("classes", "夜班");
                map.put("jth", "1#");
                map.put("jtm", "细纱机");
                map.put("cl", "0");
                map.put("nh", "0");
                map.put("dsnh", "0");
                map.put("xl", "0");
                list.add(map);
            }
        }
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> dataList = new HashMap<>();
        for (String jtId : jtIds) {
            List<Object> clList = new ArrayList<>();
            List<Object> nhList = new ArrayList<>();
            for (String date : dates) {
                clList.add(0);
                nhList.add(0);
            }
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("cl", clList);
            dataMap.put("nh", nhList);
            dataList.put(jtId, dataMap);
        }
        map.put("dataList", dataList);
        map.put("dateList", dates);
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("chart", map);
        return result;
    }

    @Override
    public Page<Object> findZbjInfo(int id) {
        Page<Object> page = SCUtil.getPage();
        List<Object> records = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("dh", "皮辊");
        map.put("tp", List.of());
        map.put("scsj", DateUtil.today());
        map.put("zt", "正常");
        map.put("ed", "0");
        map.put("yy", "0");
        map.put("sy", "0");
        map.put("bfb", String.format("%.2f", 0 / 365.0 * 100));
        records.add(map);
        page.setRecords(records);
        return page;
    }

    @Override
    public Object findWbTopInfo(int id) {
        Map<String, Object> result = new HashMap<>();
        result.put("count1", 0);
        result.put("count2", 0);
        result.put("count3", 0);
        result.put("count4", 0);
        result.put("count5", 0);
        return result;
    }

    @Override
    public Page<Object> findWbHistoryInfo(int id, String xm) {
        Page<Object> page = SCUtil.getPage();
        List<Object> records = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("xm", "揩车");
        map.put("lx", "保养");
        map.put("whzt", "已维护");
        map.put("clzt", "已做");
        map.put("whsj", DateUtil.today());
        map.put("bz", "备注");
        map.put("tp", List.of());
        map.put("ghbj", "皮辊");
        records.add(map);
        page.setRecords(records);
        return page;
    }

    @Override
    public JtjcVo selectSmJtjc() {
        return baseMapper.selectSmJtjc();
    }

    @Override
    public JtjcVo selectBtJtjc() {
        return baseMapper.selectBtJtjc();
    }

    @Override
    public JtjcVo selectCsJtjc() {
        return baseMapper.selectCsJtjc();
    }

    @Override
    public JtjcVo selectXsJtjc() {
        return baseMapper.selectXsJtjc();
    }

    @Override
    public JtjcVo selectLtJtjc() {
        return baseMapper.selectLtJtjc();
    }

    /**
     * 机台状态
     *
     * @param process
     * @return
     */
    @Override
    public List<StateVo> jtState(String process) {
        List<StateVo> list = sb02EquipmentCounterAccountMapper.selectJtState(process);
        return list;
    }

    /**
     * 机台数
     *
     * @param process
     * @param state
     * @param keyWord
     * @return
     */
    @Override
    public Map<String, Object> jtList(String process, String state, String keyWord) {
        List<JtListVo> jtListVos = sb02EquipmentCounterAccountMapper.selectJtNumber(process, state, keyWord);
        List<Integer> collect = jtListVos.stream().map(JtListVo::getId).collect(Collectors.toList());



        double result = 0.0;
        if (CollectionUtil.isNotEmpty(collect)) {
            List<Double> list = sb02EquipmentCounterAccountMapper.selectDeviceXl(collect);
            if (CollectionUtil.isNotEmpty(list)) {
                result = Math.min(list.get(0),100.0);
            }
        }

//        for (Double aDouble : list) {
//            result += aDouble;
//        }
//        result = result > 0 ? result / jtListVos.size() : 0.0;
        //保留两位小数
//        if (result > 0) {
//            result = Double.parseDouble(String.format("%.2f", result));
//        }
        Map<String, Object> map = new HashMap<>();
        map.put("xlsum", result);
        map.put("jtListVos", jtListVos);
        map.put("size", jtListVos.size());
        return map;
    }

    /**
     * 实时信息
     *
     * @param mesId
     * @param deviceName
     * @param plantForm
     * @return
     */
    @Resource(name = "ioIntensiveThreadPool")
    private ThreadPoolExecutor ioIntensiveThreadPool;
    @Autowired
    private ShachangSbStoptimeMapper shachangSbStoptimeMapper;
    @Autowired
    private DeviceRealTimeService deviceRealTimeService;

    @Override
    public Map<String, Object> realTimeMonitor(Integer mesId) {
        Map<String, Object> resultMap = new HashMap<>();
        Sb02EquipmentCounterAccount sb02EquipmentCounterAccount = sb02EquipmentCounterAccountMapper.selectSb02EquipmentCounterAccountById(mesId);
        String deviceName = sb02EquipmentCounterAccount.getDevicename();
        resultMap.put("deviceInfo", sb02EquipmentCounterAccount);

        CompletableFuture<Void> carBlockingCompletableFuture = CompletableFuture.runAsync(() -> {
            //封装挡车信息
            List<CarBlockingVo> carBlockingVoList = proPersonnelStandConfirmMapper.selectCarBlockingVo(mesId, getCurrentShift());
            CarBlockingVo carBlockingVo = getCarBlockingVo(carBlockingVoList);
            resultMap.put("carBlockingVo", carBlockingVo);
            //封装实时数据
            Object object = getRealTimeInfo(mesId, deviceName);
            //TODO:封装机台参数
            resultMap.put("jtcs", object);
        }, ioIntensiveThreadPool);
        CompletableFuture<Void> dnsjCompletableFuture = CompletableFuture.runAsync(() -> {
            //TODO：封装电能数据
            List<ElectricalEnergyDataVO> electricalEnergyDataVO = scDbRealtimeMapper.getElectricalEnergyDataVO(mesId);
            resultMap.put("dnsj", electricalEnergyDataVO);

            Assert.notNull(mesId, "机器号不能为空");
            //TODO:最近七天数据
            List<Map<String, Object>> list = deviceRealTimeService.recentlyEnergy(mesId);
            resultMap.put("recentlyEnergy", list);

        }, ioIntensiveThreadPool);
        CompletableFuture<Void> deviceCompareCompletableFuture = CompletableFuture.runAsync(() -> {
            //TODO:封装机台对比,返回机台列表
            PageHelper.startPage(1, 5);
            List<MachineVO> machineVOS = sb02EquipmentCounterAccountMapper.getMachineVOList(deviceName);
            machineVOS.removeIf(machineVO -> machineVO.getMesId().equals(mesId));//移除自己
            resultMap.put("deviceComparePlantForms", machineVOS);

        }, ioIntensiveThreadPool);

        CompletableFuture<Void> zjxxCompletableFuture = CompletableFuture.runAsync(() -> {
            //TODO：封装专件信息
            PageHelper.startPage(1, 5);
            List<SpecialInformationVO> specialInformationVOS = equipmentsparepartsMapper.getspecialInformationVOList(mesId);
            resultMap.put("zjxx", specialInformationVOS);
        }, ioIntensiveThreadPool);

        CompletableFuture<Void> sbwbCompletableFuture = CompletableFuture.runAsync(() -> {
            //TODO：封装设备维保
            Map<String, Integer> WbRecordCount = getWbRecordCount(mesId);
            resultMap.put("WbRecordCount", WbRecordCount);
        }, ioIntensiveThreadPool);

        CompletableFuture.allOf(carBlockingCompletableFuture, dnsjCompletableFuture, deviceCompareCompletableFuture, zjxxCompletableFuture, sbwbCompletableFuture).join();

        return resultMap;
    }

    @Nullable
    private static CarBlockingVo getCarBlockingVo(List<CarBlockingVo> carBlockingVoList) {
        CarBlockingVo carBlockingVo = CollectionUtil.isNotEmpty(carBlockingVoList)? carBlockingVoList.get(0):new CarBlockingVo();
        if (carBlockingVo != null) {
            String theHead = carBlockingVo.getTheHead();
            if (StringUtil.isNotEmpty(theHead)) {
                int startIndex = theHead.indexOf("\"url\":") + 8;
                int endIndex = theHead.indexOf(",", startIndex) - 1;
                String substring = theHead.substring(startIndex, endIndex);
                carBlockingVo.setTheHead(substring);
            }
        }
        return carBlockingVo;
    }


    private Map<String, Integer> getWbRecordCount(Integer mesId) {
        //TODO：封装设备维保
        Assert.notNull(mesId, "机器号不能为空");

        LocalDate now = LocalDate.now();
        String startTime = "";
        String endTime = "";
        int dayOfMonth = now.getDayOfMonth();

        if (dayOfMonth >= 20) {
            startTime = now.getYear() + "-" + now.getMonthValue() + "-" + 20;
        } else {
            startTime = now.getYear() + "-" + (now.getMonthValue() - 1) + "-" + 20;
        }
        endTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Integer curMonthWbRecordCount = sb02EquipmentCounterAccountMapper.selectMaintenance(mesId, startTime, endTime, 101);
        Integer curMonthNoWbRecordCount = sb02EquipmentCounterAccountMapper.selectMaintenance(mesId, startTime, endTime, 102);
        startTime = now.getYear() + "-1-1";
        endTime = now.getYear() + "-12-30";
        Integer curYearWbRecordCount = sb02EquipmentCounterAccountMapper.selectMaintenance(mesId, startTime, endTime, 101);
        Integer curYearWbNoRecordCount = sb02EquipmentCounterAccountMapper.selectMaintenance(mesId, startTime, endTime, 102);
        Map<String, Integer> WbRecordCount = Map.of("curMonthWbRecordCount", curMonthWbRecordCount, "curMonthNoWbRecordCount", curMonthNoWbRecordCount,
                "curYearWbRecordCount", curYearWbRecordCount, "curYearWbNoRecordCount", curYearWbNoRecordCount);
        return WbRecordCount;
    }


    /**
     * 获取机台分组
     *
     * @param process
     * @return
     */
    @Override
    public List<List> machineGroup(String process) {
        List<List> result = new ArrayList<>();
        List<Sb02EquipmentCounterAccount> list = sb02EquipmentCounterAccountMapper.machineGroup(process);
        list.sort(Comparator.comparing(Sb02EquipmentCounterAccount::getSortProcess));
        if (process.equals("细纱")) {
            List<Sb02EquipmentCounterAccount> one = list.stream().filter(item -> Integer.parseInt(item.getPlatform().replace("#", "")) <= 21).collect(Collectors.toList());
            List<Sb02EquipmentCounterAccount> two = list.stream().filter(item -> Integer.parseInt(item.getPlatform().replace("#", "")) >= 22 && Integer.parseInt(item.getPlatform().replace("#", "")) <= 42).collect(Collectors.toList());
            List<Sb02EquipmentCounterAccount> three = list.stream().filter(item -> Integer.parseInt(item.getPlatform().replace("#", "")) >= 43 && Integer.parseInt(item.getPlatform().replace("#", "")) <= 63).collect(Collectors.toList());
            List<Sb02EquipmentCounterAccount> four = list.stream().filter(item -> Integer.parseInt(item.getPlatform().replace("#", "")) >= 64 && Integer.parseInt(item.getPlatform().replace("#", "")) <= 84).collect(Collectors.toList());
            result.add(one);
            result.add(two);
            result.add(three);
            result.add(four);
        } else if (process.equals("梳棉")) {
            List<Sb02EquipmentCounterAccount> one = list.stream().filter(item -> Integer.parseInt(item.getPlatform().replace("#", "")) <= 18).collect(Collectors.toList());
            List<Sb02EquipmentCounterAccount> two = list.stream().filter(item -> Integer.parseInt(item.getPlatform().replace("#", "")) >= 19 && Integer.parseInt(item.getPlatform().replace("#", "")) <= 33).collect(Collectors.toList());
            List<Sb02EquipmentCounterAccount> three = list.stream().filter(item -> Integer.parseInt(item.getPlatform().replace("#", "")) >= 34 && Integer.parseInt(item.getPlatform().replace("#", "")) <= 52).collect(Collectors.toList());
            result.add(one);
            result.add(two);
            result.add(three);
        } else if (process.equals("络筒")) {
            List<Sb02EquipmentCounterAccount> one = list.stream().filter(item -> Integer.parseInt(item.getPlatform().replace("#", "")) <= 14).collect(Collectors.toList());
            List<Sb02EquipmentCounterAccount> two = list.stream().filter(item -> Integer.parseInt(item.getPlatform().replace("#", "")) <= 15 && Integer.parseInt(item.getPlatform().replace("#", "")) <= 28).collect(Collectors.toList());
            result.add(one);
            result.add(two);
        }
        return result;
    }

    @Override
    public List<StateVo> getDevicesState(String process) {
        List<StateVo>  stateVoList = sb02EquipmentCounterAccountMapper.getDevicesState(process);
        return stateVoList;
    }

    @Override
    public CarBlockingVo workInfo(Integer mesId, String deviceName) {
        List<CarBlockingVo> carBlockingVoList = proPersonnelStandConfirmMapper.selectCarBlockingVo(mesId, getCurrentShift());
        CarBlockingVo carBlockingVo = new CarBlockingVo();
        if (CollectionUtil.isNotEmpty(carBlockingVoList)) {
            carBlockingVo = carBlockingVoList.get(0);
        }
        return carBlockingVo;
    }

    @Override
    public Object realTime(Integer mesId, String deviceName) {
        Object object = getRealTimeInfo(mesId, deviceName);
        return object;
    }

    @Override
    public List<ProductionCapacityVo> yiledPower(Integer mesId, String deviceName) {
        com.whmskj.xjlhbc.core.Page.startPage();
        List<ProductionCapacityVo> productionCapacityVos = sb02EquipmentCounterAccountMapper.selectProductionCapacityVo(mesId);
        return productionCapacityVos;
    }

    @Override
    public List<RunStopCarVo> stopList(Integer mesId, String deviceName) {
        List<RunStopCarVo> runStopCarVos = shachangSbStoptimeMapper.selectListByMesID(mesId);
        return runStopCarVos;
    }

    @Override
    public ElectricalEnergyDataVO capacityInfo(Integer mesId, String deviceName) {
        ElectricalEnergyDataVO electricalEnergyDataVO = new ElectricalEnergyDataVO();
        List<ElectricalEnergyDataVO> electricalEnergyDataVOList = scDbRealtimeMapper.getElectricalEnergyDataVO(mesId);
        if (CollectionUtil.isNotEmpty(electricalEnergyDataVOList)) {
            electricalEnergyDataVO = electricalEnergyDataVOList.get(0);
        }
        return electricalEnergyDataVO;
    }

    @Override
    public List<MachineVO> deviceCode(Integer mesId, String deviceName) {
        List<MachineVO> machineVOS = sb02EquipmentCounterAccountMapper.getMachineVOList(deviceName);
        machineVOS.removeIf(machineVO -> machineVO.getMesId().equals(mesId));//移除自己
        return machineVOS;
    }

    @Override
    public List<ProductionCapacityVo> deviceCompareList(Integer mesId, String deviceName) {
        com.whmskj.xjlhbc.core.Page.startPage();
        List<ProductionCapacityVo> productionCapacityVoList = sb02EquipmentCounterAccountMapper.selectDeviceCompareInfo(mesId);
        return productionCapacityVoList;
    }

    @Override
    public List<SpecialInformationVO> partsList(Integer mesId, String deviceName) {
        com.whmskj.xjlhbc.core.Page.startPage();
        List<SpecialInformationVO> specialInformationVOS = equipmentsparepartsMapper.getspecialInformationVOList(mesId);
        return specialInformationVOS;
    }

    @Override
    public List<EquipmentMaintenanceVO> maintenanceList(Integer mesId, String deviceName) {
        com.whmskj.xjlhbc.core.Page.startPage();
        List<EquipmentMaintenanceVO> equipmentMaintenanceVOList = sb08tasksheetMapper.getEquipmentMaintenanceVOList(mesId);
        return equipmentMaintenanceVOList;
    }

    @Override
    public List<Map<String, Object>> deviceRunEfficiency(String dateType) {
        List<Map<String, Object>> result = new ArrayList<>();

        if ("1".equals(dateType)) {
            //近七日
            LocalDate today = LocalDate.now();
            LocalDate lastDate = today.minusDays(6);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String startTime = lastDate.format(formatter);
            String endTime = today.format(formatter);
            List<DeviceRunEfficiencyVo> list = sb02EquipmentCounterAccountMapper.selectDeviceRunEfficiency(1, startTime, endTime);
            Map<String, List<DeviceRunEfficiencyVo>> collect = list.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getWorkshop));
            List<DeviceRunEfficiencyVo> qfWorkShopList = collect.get("前纺车间");
            Map<String, List<DeviceRunEfficiencyVo>> qfEveryDayList = new HashMap<>();
            if (qfWorkShopList != null) {
                qfEveryDayList = qfWorkShopList.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getDay));
            }
            List<DeviceRunEfficiencyVo> xsWorkShopList = collect.get("细纱车间");
            Map<String, List<DeviceRunEfficiencyVo>> xsEveryDayList = new HashMap<>();
            if (xsWorkShopList != null) {
                xsEveryDayList = xsWorkShopList.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getDay));
            }
            List<DeviceRunEfficiencyVo> ltWorkShopList = collect.get("络筒车间");
            Map<String, List<DeviceRunEfficiencyVo>> ltEveryDayList = new HashMap<>();
            if (ltWorkShopList != null) {
                ltEveryDayList = ltWorkShopList.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getDay));
            }

            for (int i = 0; i < 7; i++) {
                Map<String, Object> map = new HashMap<>();
                String format = lastDate.plusDays(i).format(formatter);
                map.put("date", format);
                List<DeviceRunEfficiencyVo> qfEfficencyVoList = qfEveryDayList.get(format);
                map.put("qfWorkShop", qfEfficencyVoList != null ? qfEfficencyVoList.get(0).getEfficiency() : 0);
                List<DeviceRunEfficiencyVo> xsEfficencyVoList = xsEveryDayList.get(format);
                map.put("xsWorkShop", xsEfficencyVoList != null ? xsEfficencyVoList.get(0).getEfficiency() : 0);
                List<DeviceRunEfficiencyVo> ltEfficencyVoList = ltEveryDayList.get(format);
                map.put("ltWorkShop", ltEfficencyVoList != null ? ltEfficencyVoList.get(0).getEfficiency() : 0);
                result.add(map);
            }
        } else if ("2".equals(dateType)) {
            //近七周
            LocalDate today = null;
            for (int i = 0; i < 7; i++) {
                // 获取今天的日期
                if (today == null) {
                    today = LocalDate.now();
                }
                // 计算本周一的日期（若今天是周一，则返回今天）
                LocalDate lastDate = today.minusDays(6);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                String startTime = lastDate.format(formatter);
                String endTime = today.format(formatter);
                List<DeviceRunEfficiencyVo> list = sb02EquipmentCounterAccountMapper.selectDeviceRunEfficiency(2, startTime, endTime);
                Map<String, List<DeviceRunEfficiencyVo>> collect = list.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getWorkshop));
                List<DeviceRunEfficiencyVo> qfWorkShopList = collect.get("前纺车间");
//                Map<String, List<DeviceRunEfficiencyVo>> qfEveryDayList = new HashMap<>();
//                if (qfWorkShopList != null) {
//                    qfEveryDayList = qfWorkShopList.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getDay));
//                }
                List<DeviceRunEfficiencyVo> xsWorkShopList = collect.get("细纱车间");
//                Map<String, List<DeviceRunEfficiencyVo>> xsEveryDayList = new HashMap<>();
//                if (xsWorkShopList != null) {
//                    xsEveryDayList = xsWorkShopList.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getDay));
//                }
                List<DeviceRunEfficiencyVo> ltWorkShopList = collect.get("络筒车间");
//                Map<String, List<DeviceRunEfficiencyVo>> ltEveryDayList = new HashMap<>();
//                if (ltWorkShopList != null) {
//                    ltEveryDayList = ltWorkShopList.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getDay));
//                }

                double qfEfficency = 0.0;
                double xsEfficency = 0.0;
                double ltEfficency = 0.0;
                Map<String, Object> map = new HashMap<>();
                qfEfficency += qfWorkShopList != null ? qfWorkShopList.get(0).getEfficiency() : 0;
                xsEfficency += xsWorkShopList != null ? xsWorkShopList.get(0).getEfficiency() : 0;
                ltEfficency += ltWorkShopList != null ? ltWorkShopList.get(0).getEfficiency() : 0;


//                for (int j = 0; j < 7; j++) {
//                    String format = lastDate.plusDays(j).format(formatter);
//                    List<DeviceRunEfficiencyVo> qfEfficencyVoList = qfEveryDayList.get(format);
//                    qfEfficency += qfEfficencyVoList != null ? qfEfficencyVoList.get(0).efficiency : 0;
//                    List<DeviceRunEfficiencyVo> xsEfficencyVoList = xsEveryDayList.get(format);
//                    xsEfficency += xsEfficencyVoList != null ? xsEfficencyVoList.get(0).efficiency : 0;
//                    List<DeviceRunEfficiencyVo> ltEfficencyVoList = ltEveryDayList.get(format);
//                    ltEfficency += ltEfficencyVoList != null ? ltEfficencyVoList.get(0).efficiency : 0;
//
//                }
                map.put("date", "第" + (7 - i) + "周");
                map.put("qfWorkShop", qfEfficency);
                map.put("xsWorkShop", xsEfficency);
                map.put("ltWorkShop", ltEfficency);
                result.add(map);
                today = lastDate.minusDays(1);
            }
            Collections.reverse(result);


        } else if ("3".equals(dateType)) {
            //近七个月

            // 获取今天的日期
            LocalDate today = LocalDate.now();
            // 获取本月1号的日期
            LocalDate firstDayOfMonth = today.minusMonths(6);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            String startTime = firstDayOfMonth.format(formatter);
            String endTime = today.format(formatter);
            List<DeviceRunEfficiencyVo> list = sb02EquipmentCounterAccountMapper.selectDeviceRunEfficiency(3, startTime, endTime);
            Map<String, List<DeviceRunEfficiencyVo>> collect = list.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getWorkshop));
            Set<String> keys = collect.keySet();
            List<DeviceRunEfficiencyVo> qfWorkShopList = collect.get("前纺车间");
            Map<String, List<DeviceRunEfficiencyVo>> qfEveryDayList = new HashMap<>();
            if (qfWorkShopList != null) {
                qfEveryDayList = qfWorkShopList.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getDay));
            }
            List<DeviceRunEfficiencyVo> xsWorkShopList = collect.get("细纱车间");
            Map<String, List<DeviceRunEfficiencyVo>> xsEveryDayList = new HashMap<>();
            if (xsWorkShopList != null) {
                xsEveryDayList = xsWorkShopList.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getDay));
            }
            List<DeviceRunEfficiencyVo> ltWorkShopList = collect.get("络筒车间");
            Map<String, List<DeviceRunEfficiencyVo>> ltEveryDayList = new HashMap<>();
            if (ltWorkShopList != null) {
                ltEveryDayList = ltWorkShopList.stream().collect(Collectors.groupingBy(DeviceRunEfficiencyVo::getDay));
            }

            for (int i = 0; i < 7; i++) {
                Map<String, Object> map = new HashMap<>();
                String format = firstDayOfMonth.plusMonths(i).format(formatter);
                map.put("date", format);
                List<DeviceRunEfficiencyVo> qfEfficencyVoList = qfEveryDayList.get(format);
                map.put("qfWorkShop", qfEfficencyVoList != null ? qfEfficencyVoList.get(0).getEfficiency() : 0);
                List<DeviceRunEfficiencyVo> xsEfficencyVoList = xsEveryDayList.get(format);
                map.put("xsWorkShop", xsEfficencyVoList != null ? xsEfficencyVoList.get(0).getEfficiency() : 0);
                List<DeviceRunEfficiencyVo> ltEfficencyVoList = ltEveryDayList.get(format);
                map.put("ltWorkShop", ltEfficencyVoList != null ? ltEfficencyVoList.get(0).getEfficiency() : 0);
                result.add(map);
            }
        }
        return result;
    }

    @Override
    public List<HashMap<String, Object>> classesRunEfficiency(String startTime, String endTime) {
        List<ClassesRunEfficiencyVo> list = sb02EquipmentCounterAccountMapper.selectClassesRunEfficiency(startTime, endTime);
        Map<String, List<ClassesRunEfficiencyVo>> collect = list.stream().collect(Collectors.groupingBy(ClassesRunEfficiencyVo::getClasses));
        List<ClassesRunEfficiencyVo> jiaShift = collect.get("甲班");
        Map<String, List<ClassesRunEfficiencyVo>> jiaProcessEfficiency = new HashMap<>();
        if (jiaShift != null) {
            jiaProcessEfficiency = jiaShift.stream().collect(Collectors.groupingBy(ClassesRunEfficiencyVo::getProcess));
        }
        List<ClassesRunEfficiencyVo> yiShift = collect.get("乙班");
        Map<String, List<ClassesRunEfficiencyVo>> yiProcessEfficiency = new HashMap<>();
        if (jiaShift != null) {
            yiProcessEfficiency = yiShift.stream().collect(Collectors.groupingBy(ClassesRunEfficiencyVo::getProcess));
        }
        List<ClassesRunEfficiencyVo> bingShift = collect.get("丙班");
        Map<String, List<ClassesRunEfficiencyVo>> bingProcessEfficiency = new HashMap<>();
        if (jiaShift != null) {
            bingProcessEfficiency = bingShift.stream().collect(Collectors.groupingBy(ClassesRunEfficiencyVo::getProcess));
        }
        List<String> proceeList = List.of("头并",
                "末并",
                "粗纱",
                "细纱",
                "络筒",
                "梳棉");


        List<HashMap<String, Object>> result = new ArrayList<>();
        for (String process : proceeList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("process", process);
            map.put("jia", jiaProcessEfficiency.get(process) != null ? jiaProcessEfficiency.get(process).get(0).getEfficiency() : 0);
            map.put("yi", yiProcessEfficiency.get(process) != null ? yiProcessEfficiency.get(process).get(0).getEfficiency() : 0);
            map.put("bing", bingProcessEfficiency.get(process) != null ? bingProcessEfficiency.get(process).get(0).getEfficiency() : 0);
            result.add(map);
        }
        return result;
    }

    @Autowired
    private XsjRealtimeMapper xsjRealtimeMapper;
    @Autowired
    private CsjRealtimeMapper csjRealtimeMapper;
    @Autowired
    private LtjRealtimeMapper ltjRealtimeMapper;
    @Autowired
    private BtjRealtimeMapper btjRealtimeMapper;
    @Autowired
    private SmjRealtimeMapper smjRealtimeMapper;
    @Autowired
    private Jkm1116RealtimeMapper jkm1116RealtimeMapper;
    @Autowired
    private Hmj1024RealtimeMapper hmj1024RealtimeMapper;
    @Autowired
    private Kmj1104aRealtimeMapper kmj1104aRealtimeMapper;
    @Autowired
    private Kmj1102RealtimeMapper kmj1102RealtimeMapper;
    @Autowired
    private Zmj1018RealtimeMapper zmj1018RealtimeMapper;

    public List<RealTimeVo> getRealTimeVoList(LinkedHashMap<String, Object> linkedHashMap) {
        List<RealTimeVo> resultList = new ArrayList<>();
        Set<String> names = linkedHashMap.keySet();
        for (String name : names) {
            Object value = linkedHashMap.get(name);
            RealTimeVo realTimeVo = new RealTimeVo();
            realTimeVo.setName(name);
            String replace = value.toString().replace("T", " ");
            realTimeVo.setValue(replace);
            resultList.add(realTimeVo);
        }
        return resultList;
    }

    private HashMap<String, Object> getRealTimeInfo(Integer mesId, String deviceName) {
        HashMap<String, Object> resultMap = new HashMap<>();
        if (deviceName.equals("细纱机")) {
            LinkedHashMap<String, Object> realtimeMap = xsjRealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            LinkedHashMap<String, Object> deviceParamInfo = xsjRealtimeMapper.selectDeviceParamInfo(mesId);
            List<RealTimeVo> realTimeVoList1 = getRealTimeVoList(deviceParamInfo);
            String readTime = xsjRealtimeMapper.selectReadTime(mesId);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", realTimeVoList1);
            resultMap.put("readTime", readTime);
        } else if (deviceName.equals("粗纱机")) {
            LinkedHashMap<String, Object> realtimeMap = csjRealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            LinkedHashMap<String, Object> deviceParamInfo = csjRealtimeMapper.selectDeviceParamInfo(mesId);
            List<RealTimeVo> realTimeVoList1 = getRealTimeVoList(deviceParamInfo);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", realTimeVoList1);
            String readTime = csjRealtimeMapper.selectReadTime(mesId);
            resultMap.put("readTime", readTime);
        } else if (deviceName.equals("络筒机")) {

            LinkedHashMap<String, Object> realtimeMap = ltjRealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", null);
            String readTime = ltjRealtimeMapper.selectReadTime(mesId);
            resultMap.put("readTime", readTime);

        } else if (deviceName.equals("预并条") || deviceName.equals("末并")) {
            LinkedHashMap<String, Object> realtimeMap = btjRealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            LinkedHashMap<String, Object> deviceParamInfo = btjRealtimeMapper.selectDeviceParamInfo(mesId);
            List<RealTimeVo> realTimeVoList1 = getRealTimeVoList(deviceParamInfo);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", realTimeVoList1);
            String readTime = btjRealtimeMapper.selectReadTime(mesId);
            resultMap.put("readTime", readTime);

        } else if (deviceName.equals("梳棉机")) {
            LinkedHashMap<String, Object> realtimeMap = smjRealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            LinkedHashMap<String, Object> deviceParamInfo = smjRealtimeMapper.selectDeviceParamInfo(mesId);
            List<RealTimeVo> realTimeVoList1 = getRealTimeVoList(deviceParamInfo);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", realTimeVoList1);
            String readTime = smjRealtimeMapper.selectReadTime(mesId);
            resultMap.put("readTime", readTime);

        } else if (deviceName.equals("精开棉机")) {
            LinkedHashMap<String, Object> realtimeMap = jkm1116RealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            LinkedHashMap<String, Object> deviceParamInfo = jkm1116RealtimeMapper.selectDeviceParamInfo(mesId);
            List<RealTimeVo> realTimeVoList1 = getRealTimeVoList(deviceParamInfo);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", realTimeVoList1);
            String readTime = jkm1116RealtimeMapper.selectReadTime(mesId);
            resultMap.put("readTime", readTime);


        } else if (deviceName.equals("多仓混棉机")) {

            LinkedHashMap<String, Object> realtimeMap = hmj1024RealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            LinkedHashMap<String, Object> deviceParamInfo = hmj1024RealtimeMapper.selectDeviceParamInfo(mesId);
            List<RealTimeVo> realTimeVoList1 = getRealTimeVoList(deviceParamInfo);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", realTimeVoList1);

            String readTime = hmj1024RealtimeMapper.selectReadTime(mesId);
            resultMap.put("readTime", readTime);

        } else if (deviceName.equals("开棉机1104")) {

            LinkedHashMap<String, Object> realtimeMap = kmj1104aRealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            LinkedHashMap<String, Object> deviceParamInfo = kmj1104aRealtimeMapper.selectDeviceParamInfo(mesId);
            List<RealTimeVo> realTimeVoList1 = getRealTimeVoList(deviceParamInfo);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", realTimeVoList1);

            String readTime = kmj1104aRealtimeMapper.selectReadTime(mesId);
            resultMap.put("readTime", readTime);
        } else if (deviceName.equals("开棉机1102")) {


            LinkedHashMap<String, Object> realtimeMap = kmj1102RealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            LinkedHashMap<String, Object> deviceParamInfo = kmj1102RealtimeMapper.selectDeviceParamInfo(mesId);
            List<RealTimeVo> realTimeVoList1 = getRealTimeVoList(deviceParamInfo);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", realTimeVoList1);

            String readTime = kmj1102RealtimeMapper.selectReadTime(mesId);
            resultMap.put("readTime", readTime);

        } else if (deviceName.equals("抓棉机")) {
            LinkedHashMap<String, Object> realtimeMap = zmj1018RealtimeMapper.selectRealTimeInfo(mesId);
            Assert.isTrue(CollectionUtil.isNotEmpty(realtimeMap), "该机器在实时表中没有数据");
            List<RealTimeVo> realTimeVoList = getRealTimeVoList(realtimeMap);
            LinkedHashMap<String, Object> deviceParamInfo = zmj1018RealtimeMapper.selectDeviceParamInfo(mesId);
            List<RealTimeVo> realTimeVoList1 = getRealTimeVoList(deviceParamInfo);
            resultMap.put("deviceRealInfo", realTimeVoList);
            resultMap.put("deviceParamInfo", realTimeVoList1);

            String readTime = zmj1018RealtimeMapper.selectReadTime(mesId);
            resultMap.put("readTime", readTime);
        } else {
            throw new RuntimeException("扫码机器不存在实时表");
        }
        return resultMap;
    }

    //获取班次
    public static String getCurrentShift() {
        // 获取当前时间
        LocalTime now = LocalTime.now();

        // 定义早班开始时间(9:30)和结束时间(21:30)
        LocalTime morningStart = LocalTime.of(9, 30);
        LocalTime eveningStart = LocalTime.of(21, 30);

        // 判断当前时间是否在9:30到21:30之间
        boolean isMorningShift = now.isAfter(morningStart) && now.isBefore(eveningStart);

        // 注意：这里使用isBefore判断21:30，所以21:30整会被归为晚班
        // 如果需要21:30整仍算早班，可以改为now.compareTo(eveningStart) <= 0

        return isMorningShift ? "早班" : "晚班";
    }

    private CorpMember getCorpMember() {
        String userId = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CorpMember::getUserId, userId).last("limit 1");
        return corpMemberMapper.selectOne(wrapper);
    }


    private List<String> get(LocalDate start, LocalDate end) {
        List<String> dates = new ArrayList<>();
        while (!start.isAfter(end)) {
            dates.add(start.toString());
            start = start.plusDays(1);
        }
        return dates;
    }


    private List<String> get() {
        List<String> dates = new ArrayList<>();
        LocalDate end = LocalDate.now();
        LocalDate start = end.minusDays(30);
        while (!start.isAfter(end)) {
            dates.add(start.toString());
            start = start.plusDays(1);
        }
        return dates;
    }
}
